﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Summer.Exception;

#region License
/*
 *  Copyright (c) Dumuzi.cn 2009 , All rights reserved.
 *  CLR Version: 2.0.50727.4927
 *  NameSpace: Summer.Object
 *  Author:Edwin Tai,戴佳顺
 *  Msn:edwin19861218@hotmail.com
 *  QQ: 1961218
 *  Date:2009-11-17 16:14:35
 *  Licensed under the Microsoft Public License (Ms-PL)
 *  This license governs use of the accompanying software. 
 *  If you use the software, you accept this license.
 *  If you do not accept the license, do not use the software.
 */
#endregion

namespace Summer.Object
{
    public static class ExtensionData
    {
        /// <summary>
        /// Merge two array
        /// The two should be the same type
        /// </summary>
        /// <param name="root">the root array</param>
        /// <param name="branch">the array to merge</param>
        /// <returns>new instance of array with the two elements</returns>
        public static Array MergeArray(this Array root, Array branch)
        {
            if (root.GetType() != branch.GetType())
            {
                throw new IocException("The types of two arrays are not the same");
            }
            ArrayList list = new ArrayList();
            Type t = null;
            if (root != null && root.Length != 0)
            {
                t = root.GetValue(0).GetType();
                foreach (var o in root) { list.Add(o); }
            }
            if (branch != null && branch.Length != 0)
            {
                t = branch.GetValue(0).GetType();
                foreach (var o in branch) { list.Add(o); }
            }
            if (list.Count == 0)
            {
                return root;
            }
            return list.ToArray(t);
        }
        /// <summary>
        /// Copy the array to a list
        /// </summary>
        /// <param name="ar">Array with elements</param>
        /// <param name="list">List to copy</param>
        public static void CopyTo(this Array ar, ArrayList list)
        {
            CopyTo(ar, list, (object o) => { return true; });
        }
        /// <summary>
        /// Copy the array to a list
        /// </summary>
        /// <param name="ar">Array with elements</param>
        /// <param name="list">List to copy</param>
        /// <param name="fc">
        /// The logic to judge whether to copy
        /// <param name="o">The element when meet</param>
        /// <returns>if true,copy ;else miss</returns>
        /// </param>
        public static void CopyTo(this Array ar, ArrayList list,Func<object,bool> fc)
        {
            foreach (var a in ar)
            {
                if (fc(a))
                {
                    list.Add(a);
                }
            }
        }
    }
}
